package com.huai.jt1078.controller;

import cn.hutool.core.util.StrUtil;
import com.huai.jt1078.config.VideoConfig;
import com.huai.jt1078.endpoint.IntercomWebSocket;
import com.huai.jt1078.entity.vo.ResultVO;
import com.huai.jt1078.entity.vo.VideoUrlVO;
import com.huai.jt1078.enums.VideoType;
import com.huai.jt1078.utils.JedisUtil;

import com.huai.jt1078.utils.SessionManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xingkong
 * @program jt1078
 * @description rtmp相关接口
 * @date 2021-09-13 13:50
 **/
@Slf4j
@Api(tags = "RTMP相关接口")
@RestController("rtmp")
public class RtmpController {


    @Autowired
    VideoConfig videoConfig;
    /**
     * 获取视频推送地址
     * @param type 视频类型
     * @param  tag 视频tag
     * @author xingkong
     * @date 2021-09-13 13:57
     * @return 视频播放地址
     */
    @GetMapping("/url/{type}/{tag}")
    @ApiOperation("根据音视频类型和tag获取播放地址")
    public ResultVO<VideoUrlVO> getUrl(@PathVariable String type,@PathVariable String tag){
        String url = videoConfig.getUrl(type);

       // String url = null;//PropertiesUtil.get(urlKey);
        if (StrUtil.isBlank(url)){
            return ResultVO.fail("请求视频格式错误");
        }
        url = String.format(url,tag);
        VideoUrlVO urlVO = VideoUrlVO.builder().serverIp(videoConfig.getServerIp())
                .serverPort(videoConfig.getServerPort()).videoUrl(url).build();
        if (VideoType.AUDIO.getType().equals(type)){
            // 判断当前是否已经存在语音对讲
            if (IntercomWebSocket.TAG_MAP.containsKey(tag)){
//                throw new RuntimeException("当前设备已存在语音对讲，请稍后");
            }
            urlVO.setWebSocketUrl(String.format(videoConfig.getWsUrl(),tag));
            SessionManager.instance.getAudioMap().add(tag);
        }

        log.info("请求数据类型：{} tag:{} 返回地址：{}",type,tag,url);
        return ResultVO.ok(urlVO);
    }

    /**
     * 心跳检测
     * @param tag 视频tag
     * @author xingkong
     * @date 2021-09-13 14:00
     * @return在
     */
    @GetMapping("/heartbeat/{tag}")
    @ApiOperation("心跳接口")
    public ResultVO<String> heartbeat(@PathVariable String tag){
        JedisUtil.set(tag,tag,60);
        return ResultVO.ok();
    }

}
